package com.ddwl.message.service;

import com.ddwl.common.constant.RedisKey;
import com.ddwl.common.exception.CommonException;
import com.ddwl.common.service.RedisService;
import com.ddwl.common.util.RandomGenerateUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.message.domain.sms.dao.SentSmsFlowDao;
import com.ddwl.message.domain.sms.dao.model.SmsSentFlow;
import com.ddwl.message.util.AliYunSmsSender;
import com.ddwl.schema.bo.gate.SmsBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Fu Zhaohui
 * @date 2017/1/3
 */
@Slf4j
@Service
public class SmsService {

    @Resource
    private RedisService redisService;
    @Resource
    private AliYunSmsSender aliYunSmsSender;
    @Resource
    private SentSmsFlowDao sentSmsFlowDao;

    @Transactional(rollbackFor = Throwable.class)
    public void getAuthCode(SmsBo bo) {
        List<String> mobiles = redisService.getListOps().range("blacklist", 0, -1);
        String mobile = bo.getMobile();
        if (mobiles != null && mobiles.contains(mobile)) {
            throw new CommonException("非法参数");
        }
        String key = RedisKey.MOBILE_KEY.getKey(mobile);
        String code = redisService.getValueOps().get(key);
        if (StringUtils.hasText(code)) {
            throw new CommonException("验证码已发送，请查看短信箱");
        }
        code = RandomGenerateUtil.getRandomS(1, 4);
        aliYunSmsSender.sendCode(mobile, code);
        redisService.getValueOps().set(key, code, 5, TimeUnit.MINUTES);
    }

    public void changeId() {
        List<SmsSentFlow> list=sentSmsFlowDao.getAll();
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, String> map = new HashMap<>();
            for (SmsSentFlow ssf : list) {
                String id = ssf.getId();
                if (id.length() == 11) {
                    long longId = UUIDGenerator.reverseShortUUID(id);
                    map.put(id, String.valueOf(longId));
                }
            }
            if (!map.isEmpty()) {
                sentSmsFlowDao.changeId(map);
            }
        }
    }
}
